﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Interfaces.System;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SHZY.BaseData.Interfaces.Common;
using SHZY.BaseData.Entitys.Common.Entity;
using SHZY.BaseData.Entitys.Common.Dto.PrintConfig;
using System.Linq;

namespace SHZY.BaseData.Common;

/// <summary>
/// 业务实现：打印配置.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "PrintConfig", Order = 200)]
[Route("api/Common/BaseData/[controller]")]
public class ComBasePrintConfigService : IComBasePrintConfigService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<ComBasePrintConfigEntity> _repository;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="ComBasePrintConfigService"/>类型的新实例.
    /// </summary>
    public ComBasePrintConfigService(
        ISqlSugarRepository<ComBasePrintConfigEntity> comBasePrintConfigRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = comBasePrintConfigRepository;
        _dataInterfaceService = dataInterfaceService;
        _userManager = userManager;
        _db = context.AsTenant();
    }

    /// <summary>
    /// 获取打印配置.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<ComBasePrintConfigInfoOutput>();
    }

    /// <summary>
    /// 获取打印配置列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] ComBasePrintConfigListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<ComBasePrintConfigEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.name), it => it.Name.Contains(input.name))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.Name.Contains(input.keyword))
            //.OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
            .Where(it => it.DeleteMark == null).Select(it => new ComBasePrintConfigListOutput
            {
                id = it.Id,
                code = it.Code,
                name = it.Name,
                printTemplateId = SqlFunc.Subqueryable<ComBasePrintTemplateEntity>().Where(s => s.Id == it.PrintTemplateId).Select(s => s.FullName),
                isCustomer = SqlFunc.IIF(it.IsCustomer == 0, "否", "是"),
                dataSourceId = SqlFunc.Subqueryable<ComBasePrintDataEntity>().Where(s => s.Id == it.DataSourceId).Select(s => s.Name),
                labelRulerTemplate = it.LabelRulerTemplate,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "停用", "正常"),
            }).MergeTable();
        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        else
        {
            queryable.OrderBy(it => it.id);
        }
        var data = await queryable.ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<ComBasePrintConfigListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建打印配置.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] ComBasePrintConfigCrInput input)
    {
        input.code = input.code.Trim();
        input.name = input.name.Trim();
        if (await _repository.AnyAsync(x => (x.Code == input.code || x.Name == input.name || (x.PrintTemplateId == input.printTemplateId && x.DataSourceId == input.dataSourceId)) && x.DeleteMark == null))
            throw Oops.Oh(ErrorCode.COM1004);
        var entity = input.Adapt<ComBasePrintConfigEntity>();
        entity.Id = SnowflakeIdHelper.NextId();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 更新打印配置.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] ComBasePrintConfigUpInput input)
    {
        //|| x.PrintTemplateId == input.printTemplateId 暂时去除数据源控制
        if (await _repository.AnyAsync(x => (x.Code == input.code || x.Name == input.name || (x.PrintTemplateId == input.printTemplateId && x.DataSourceId == input.dataSourceId)) && x.DeleteMark == null && x.Id != input.id))
            throw Oops.Oh(ErrorCode.COM1004);
        var entity = input.Adapt<ComBasePrintConfigEntity>();
        var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
        {
            it.Code,
            it.Name,
            it.PrintTemplateId,
            it.IsCustomer,
            it.DataSourceId,
            it.LabelRulerTemplate,
            it.EnabledMark,
        }).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除打印配置.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Updateable<ComBasePrintConfigEntity>().SetColumns(it => new ComBasePrintConfigEntity()
        {
            DeleteTime = DateTime.Now,
            DeleteMark = 1,
            DeleteUserId = _userManager.UserId
        }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
        if (!isOk) throw Oops.Oh(ErrorCode.COM1002);
    }

    /// <summary>
    /// 批量删除打印配置.
    /// </summary>
    /// <param name="ids">主键数组.</param>
    /// <returns></returns>
    [HttpPost("batchRemove")]
    public async Task BatchRemove([FromBody] List<string> ids)
    {
        var entitys = await _repository.Context.Queryable<ComBasePrintConfigEntity>().In(it => it.Id, ids).ToListAsync();
        if (entitys.Count > 0)
        {
            try
            {
                // 开启事务
                _db.BeginTran();

                // 批量删除客户信息
                var isOk = await _repository.Context.Updateable<ComBasePrintConfigEntity>().SetColumns(it => new ComBasePrintConfigEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(it => ids.Contains(it.Id)).ExecuteCommandHasChangeAsync();

                // 关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                // 回滚事务
                _db.RollbackTran();

                throw Oops.Oh(ErrorCode.COM1002);
            }
        }
    }
}